# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from PIL import Image
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline


class FirstPipeline:
    def process_item(self, item, spider):
        return item

#自定义的图片下载类需要继承于ImagesPipeline
class TubatuImagePipeline(ImagesPipeline):
    # def get_media_requests(self, item, info):
    #     #根据image_urls中指定的URL进行爬取
    #     pass
    def __init__(self, *args, **kwargs):
        super(TubatuImagePipeline, self).__init__(*args, **kwargs)
        # 设置更高的像素限制
        Image.MAX_IMAGE_PIXELS = 500000000  # 5亿像素
    def item_completed(self, results, item, info):
        #图片下载完毕之后，处理结果的,返回是一个二元组
        #(success,image_info_or_failure)
        image_paths = [x['path'] for ok,x in results if ok]
        if not image_paths:
            raise DropItem('Item contains no images')
        return item

    def file_path(self, request, response=None, info=None):
        #用于给下载的图片设置文件名称的
        url = request.url
        file_name = url.split('/')[-1]
        #aaaa.jpg
        return file_name
